<?php

namespace app\admin\controller\device;

use app\common\controller\Backend;
use think\Db;
use fast\Http;
use think\Log;
use app\admin\model\Admin;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use fast\Tree;

/**
 * 功能管理
 *
 * @icon fa fa-users
 */
class Devicelist extends Backend
{

    /**
     * @var \app\admin\model\UserGroup
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Device');
        $group_id = Db::name('auth_group_access')->where('uid',$this->auth->id)->value('group_id');
        $devicelist = $this->model->where(['admin_id'=>$this->auth->id])->order('id DESC')->find();
        if (!$devicelist || $devicelist['update_dt']<date('Y-m-d').' 00:00:00') {
            $adminuser = Admin::where('id',$this->auth->id)->field('id,token_type,access_token')->find();
            if ($adminuser) {
                $url = config('device_domain').'/api/nx-iot/card/list';
                $param = json_encode(['index'=>1,'size'=>20]);
                $header = array('Content-Type: application/json; charset=utf-8',
                    'Content-Length:' . strlen($param),'Authorization:'.$adminuser->token_type.' '.$adminuser->access_token);
                $res = Http::post($url,$param,[],$header);
                $result = json_decode($res,1);
                if (isset($result['code']) && $result['code']==401) { // 登录过期
                    $this->auth->logout();
                    Hook::listen("admin_logout_after", $this->request);
                    $html = "<form id='logout_submit' name='logout_submit' action='' method='post'>" . token() . "<input type='submit' value='ok' style='display:none;'></form>";
                    $html .= "<script>document.forms['logout_submit'].submit();</script>";
                    return $html;
                }
                if (isset($result['list']) && count($result['list'])>0) {
                    if (!$devicelist) $devicelist = model('Device');
                    $devicelist->admin_id = $this->auth->id;
                    $devicelist->group_id = $group_id;
                    $devicelist->content = $res;
                    $devicelist->save();
                }
            }
        }
        $this->devicelist = $devicelist;
        $this->content = [];
        $this->operation = [];
        if (isset($devicelist['content']) && $devicelist['content']) {
            $this->content = json_decode($devicelist['content'],1);
        }
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where('admin_id',$this->auth->id)
                ->order($sort, $order)
                ->find();
            $contentlist = [];
            $content = json_decode($list['content'],1);
            foreach ($content['list'] as $k => $v) {
                if (isset($v['children'])) {
                    foreach ($v['children'] as $key => $value) {
                        $contentlist[] = $value;
                    }
                } else {
                    $contentlist[] = $v;
                }
            }
            foreach ($contentlist as &$v3) {
                $v3['img'] = '';
                $row = Db::name('device_list')->where('device_id',$v3['id'])->find();
                if (isset($row['img'])) {
                    $v3['img'] = config('upload_domain').$row['img'];
                }
            }
            $result = array("total" => $limit, "rows" => $contentlist);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $params = $post['row'];
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if (!$params['img'] || !$params['device_id']) {
                        $this->error('缺少参数');
                    }
                    foreach ($this->content['list'] as $k => $v) {
                        if (isset($v['children'])) {
                            foreach ($v['children'] as $key => $value) {
                                if ($params['device_id']==$value['id']) {
                                    $row = Db::name('device_list')->where('device_id',$value['id'])->find();
                                    if ($row) {
                                        $data = [
                                            'img' => $params['img'],
                                            'update_dt' => date('Y-m-d H:i:s'),
                                        ];
                                        $result = Db::name('device_list')->where('device_id',$value['id'])->update($data);
                                    } else {
                                        $data = [
                                            'title' => $value['name'],
                                            'status' => 1,
                                            'admin_id' => $this->auth->id,
                                            'device_id' => $value['id'],
                                            'img' => $params['img'],
                                            'create_dt' => date('Y-m-d H:i:s'),
                                        ];
                                        $result = Db::name('device_list')->insert($data);
                                    }
                                }
                            }
                        } else {
                            if ($params['device_id']==$v['id']) {
                                $row = Db::name('device_list')->where('device_id',$v['id'])->find();
                                if ($row) {
                                    $data = [
                                        'img' => $params['img'],
                                        'update_dt' => date('Y-m-d H:i:s'),
                                    ];
                                    $result = Db::name('device_list')->where('device_id',$v['id'])->update($data);
                                } else {
                                    $data = [
                                        'title' => $v['name'],
                                        'status' => 1,
                                        'admin_id' => $this->auth->id,
                                        'device_id' => $v['id'],
                                        'img' => $params['img'],
                                        'create_dt' => date('Y-m-d H:i:s'),
                                    ];
                                    $result = Db::name('device_list')->insert($data);
                                }
                            }
                        }
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        foreach ($this->content['list'] as $k => $v) {
            if (isset($v['children'])) {
                foreach ($v['children'] as $key => $value) {
                    if ($ids==$value['id']) {
                        $row = Db::name('device_list')->where('device_id',$value['id'])->find();break;
                    }
                }
            } else {
                if ($ids==$v['id']) {
                    $row = Db::name('device_list')->where('device_id',$v['id'])->find();break;
                }
            }
        }
        if (!isset($row)) {
            $row = ['img'=>'','device_id'=>$ids];
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values) {
                    $adminIds = $this->getDataLimitAdminIds();
                    if (is_array($adminIds)) {
                        $this->model->where($this->dataLimitField, 'in', $adminIds);
                    }
                    $count = 0;
                    Db::startTrans();
                    try {
                        if ($this->devicelist) {
                            $this->operation[$ids]['status'] = $values['status'];
                            // if (!in_array($ids, $this->operation)) {
                            //     $this->operation[$ids]['name'] = '';
                            // }
                            $this->devicelist->operation = json_encode($this->operation);
                            $count = $this->devicelist->save();
                        }
                        Db::commit();
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($count) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
